# -*- python -*-
# ex: set syntax=python:

# This is a buildmaster config file. It must be installed as
# 'master.cfg' in buildmaster's base directory.

# This is the dictionary that the buildmaster pays attention to. We also use
# a shorter alias to save typing.
c = BuildmasterConfig = {}

####### BUILDSLAVES

# The 'slaves' list defines the set of recognized buildslaves. Each element is
# a BuildSlave object, specifying a unique slave name and password.  The same
# slave name and password must be configured on the slave.
from buildbot.buildslave import BuildSlave
c['slaves'] = [
  BuildSlave("lucid32", "pass"),
  BuildSlave("lucid64", "pass"),
  BuildSlave("precise32", "pass"),
  BuildSlave("precise64", "pass"),
  BuildSlave("trusty32", "pass"),
  BuildSlave("trusty64", "pass"),
  BuildSlave("xenial32", "pass"),
  BuildSlave("xenial64", "pass"),
  BuildSlave("osx-ml", "pass"),
  BuildSlave("win2008", "pass")]
plinux32 = ["lucid32", "precise32", "trusty32", "xenial32"]
plinux64 = ["lucid64", "precise64", "trusty64", "xenial64"]

# 'slavePortnum' defines the TCP port to listen on for connections from slaves.
# This must match the value configured into the buildslaves (with their
# --master option)
c['slavePortnum'] = 9989

####### CHANGESOURCES, BUILDERS AND SCHEDULERS

# The 'builders' list defines the Builders, which tell Buildbot how
# to perform a build: what steps, and which slaves can execute them.
#  Note that any particular build will only take place on one slave.

from buildbot.changes.gitpoller import GitPoller
from buildbot.process.factory import BuildFactory
from buildbot.config import BuilderConfig
from buildbot.steps.source.git import Git
from buildbot.steps.shell import ShellCommand
from buildbot.steps.shell import Configure
from buildbot.steps.shell import Compile
from buildbot.steps.shell import Test
from buildbot.steps.transfer import FileUpload
from buildbot.schedulers.basic import SingleBranchScheduler
from buildbot.schedulers.forcesched import ForceScheduler
from buildbot.schedulers.trysched import Try_Userpass
from buildbot.changes import filter
from twisted.python import log
import os, re

def extract_warnings(step, line, match):
  file = "<unknown>"
  lineno = None
  message = line
  patterns = [
    r'(.+):([0-9]+):(?:[0-9]+:) (?:warning|note): (.+)',
    r'(.+):([0-9]+): warning: (.+)',
    r'(.+)\(([0-9]+)\): warning (.+)',
    r'(.+)() : warning (.+)']
  for p in patterns:
    m = re.match(p, line)
    if m:
      file = m.group(1)
      if m.group(2) != '':
        lineno = int(m.group(2))
      message = m.group(3)
      break
  file = file.strip().replace('\\', '/')
  #log.msg("warning file: {} line: {} message: {}".format(file, lineno, message))
  return (file, lineno, message)

platforms = {
  'trusty32': 'trusty32',
  'trusty64': 'trusty64',
  'xenial32': 'xenial32',
  'xenial64': 'xenial64',
  'osx': 'osx-ml',
  'win32': 'win2008',
  'win64': 'win2008',
}

c['change_source'] = []
c['schedulers'] = []
c['builders'] = []

def add_schedulers(project, builders):
  c['schedulers'].append(SingleBranchScheduler(
    name=project + "-master",
    change_filter=filter.ChangeFilter(project=project, branch='master'),
    treeStableTimer=None,
    builderNames=builders))
  c['schedulers'].append(SingleBranchScheduler(
    name=project + "-develop",
    change_filter=filter.ChangeFilter(project=project, branch='develop'),
    treeStableTimer=None,
    builderNames=builders))
  c['schedulers'].append(SingleBranchScheduler(
    name=project + "-testing",
    change_filter=filter.ChangeFilter(project=project, branch='testing'),
    treeStableTimer=None,
    builderNames=builders))
  c['schedulers'].append(ForceScheduler(
    name=project + "-force",
    builderNames=builders))
  c['schedulers'].append(
    Try_Userpass(name=project + '-try',
                 builderNames=builders,
                 port=5555,
                 userpass=[(project, project)]))

class Upload:
  def __init__(self, path, **kwargs):
    self.path = path
    self.platform = kwargs.get('platform')
    self.platforms = kwargs.get('platforms')

def add_build_steps(project, factory, platform, debug, **kwargs):
  # Configure.
  cmake_cmd = ["cmake"]
  osx = platform.startswith("osx")
  win32 = platform.startswith("win")
  cmake_args = kwargs.pop("cmake_args", [])
  cmake_args_osx = kwargs.pop("cmake_args_osx", [])
  cmake_args_win32 = kwargs.pop("cmake_args_win32", [])
  cmake_args_linux = kwargs.pop("cmake_args_linux", [])
  if osx:
    cmake_cmd += [
      "-DCMAKE_OSX_DEPLOYMENT_TARGET=10.7",
      "-DCMAKE_OSX_SYSROOT=/opt/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.7.sdk"]
    cmake_cmd += cmake_args_osx
  elif win32:
    cmake_cmd = [
      "cmake", "-DMP_WINSDK=TRUE",
      "-G", "Visual Studio 10" + (" Win64" if platform == "win64" else "")]
    cmake_cmd += cmake_args_win32
  else:
    cmake_cmd += cmake_args_linux
  cmake_cmd += cmake_args
  if debug:
    cmake_cmd.append("-DCMAKE_BUILD_TYPE=Debug")
  # Unset MACOSX_DEPLOYMENT_TARGET to avoid CMake error.
  factory.addStep(Configure(command=cmake_cmd + ["."],
                            env={"MACOSX_DEPLOYMENT_TARGET": ""}))
  # Compile.
  compile_args = kwargs
  if not "command" in compile_args:
    compile_args["command"] = ["make", "all"]
  if win32:
    config = "/p:Configuration=" + ("Debug" if debug else "Release")
    extra_targets = compile_args["command"][2:]
    msbuild_cmd = ["run-msbuild", config, "/clp:NoSummary"]
    sln_file = project.upper().replace("-", "_") + ".sln"
    compile_args["command"] = msbuild_cmd + [sln_file]
  factory.addStep(Compile(**compile_args))
  if win32:
    for target in extra_targets:
      compile_args = compile_args.copy()
      cmd = compile_args["command"] = compile_args["command"][:]
      cmd[-1] = target + ".vcxproj"
      factory.addStep(Compile(**compile_args))
  # Run tests.
  test_cmd = ["make", "test"] if not win32 else \
              msbuild_cmd + ["RUN_TESTS.vcxproj"]
  factory.addStep(Test(command=test_cmd, env={'CTEST_OUTPUT_ON_FAILURE': '1'},
    logfiles={"testlog": "Testing/Temporary/LastTest.log"}))


def add_project(project, uploads=[], extra_builders=[], **kwargs):
  """Adds change sources, builders and schedulers for a project."""
  url = kwargs.pop("url", "git://github.com/ampl/" + project + ".git")
  c['change_source'].append(
    GitPoller(url.replace("{master}", "localhost"), project=project,
      workdir='gitpoller-workdir-' + project, branches=['master', 'develop', 'testing'],
      pollinterval=120))
  builders = extra_builders[:]
  debug_flags = [False]
  if kwargs.pop("debug", True):
    debug_flags.append(True)
  submodule_command = kwargs.pop("submodule_command", None)
  use_submodules = kwargs.pop("use_submodules", True)
  build_steps = kwargs.pop("build_steps", add_build_steps)
  for platform, slave in platforms.iteritems():
    master_ip = "172.17.42.1" if platform.startswith("linux") else "10.0.2.2"
    adjusted_url = url.replace("{master}", master_ip)
    for debug in debug_flags:
      factory = BuildFactory()
      win32 = platform.startswith("win")
      # Get source.
      factory.addStep(Git(repourl=adjusted_url, mode="full", method="fresh"))
      if submodule_command:
        factory.addStep(ShellCommand(command=submodule_command, workdir="build"))
        factory.addStep(ShellCommand(command=["git", "submodule", "sync"], workdir="build"))
      if use_submodules:
        factory.addStep(ShellCommand(
          command=["git", "submodule", "foreach", "--recursive", "git", "reset", "--hard"], workdir="build"))
        factory.addStep(ShellCommand(
          command=["git", "submodule", "update", "--init", "--recursive"], workdir="build"))
      build_steps(project, factory, platform, debug, **kwargs)
      # Upload files to master.
      if not debug:
        for upload in uploads:
          if isinstance(upload, basestring):
            upload = Upload(upload)
          path = upload.path
          if upload.platform and not platform.startswith(upload.platform):
            continue
          elif upload.platforms and platform not in upload.platforms:
            continue
          release = False # Whether file is in Release subdirectory.
          if win32:
            ext = os.path.splitext(path)[1]
            release = ext == "" or ext == ".dll"
            if ext == "":
              path += ".exe"
          dirname, filename = os.path.split(path)
          if release:
            path = os.path.join(dirname, "Release", filename)
          factory.addStep(FileUpload(slavesrc=path,
            masterdest=os.path.join("~", "upload", platform, project, filename),
            mode=0755))
      # Create builder.
      builder = project + "-" + platform
      if debug:
        builder = "~" + builder + "-debug"
      builders.append(builder)
      c['builders'].append(BuilderConfig(name=builder,
        category=project, slavenames=[slave], factory=factory))
  add_schedulers(project, builders)

# AMPL
uploads = [
  "bin/amplgsl.dll",
  "src/gsl/gsl.ampl",
  "bin/ampltabl.dll",
  "src/cp/cp.ampl",
  "bin/cp.dll",
  "bin/gecode",
  "solvers/gecode/gecode.ampl",
  "bin/jacop",
  "bin/ampljacop.jar",
  "thirdparty/jacop/jacop-4.1.0.jar",
  "bin/localsolver",
  Upload("bin/localsolver.dll", platform="win"),
  "bin/path",
  Upload("bin/path47.dll", platform="win"),
  "versions.txt"]

for basename in ['amplfunc', 'spamfunc']:
  name = 'bin/' + basename + '.mex'
  uploads += [
    Upload(name + "a64", platforms=plinux64),
    Upload(name + "w32", platform="win32"),
    Upload(name + "w64", platform="win64"),
    Upload(name + "maci64", platform="osx")]

add_project("mp", uploads,
    cmake_args=["-DBUILD=all"],
    command=["make", "all", "versions"],
    warningPattern='.*[Ww]arning.*',
    warningExtractor=extract_warnings,
    suppressionFile="support/buildbot/warnings.supp")

# COIN-OR solvers (built separately because very time consuming).
uploads = [
  "bin/cbc",
  "bin/ipopt",
  Upload("bin/libipoptfort.dll", platform="win"),
  "bin/bonmin",
  "bin/couenne",
  "coin-versions.txt"]
add_project("coin", uploads,
  command=["make", "all", "coin-versions"], warningPattern='.*[Ww]warning.*')

add_project("gsl",
  cmake_args_win32=["-DBUILD_SHARED_LIBS:BOOL=ON"],
  warningPattern='.*[Ww]warning.*'
)

import key

# AMPL IDE.
def add_amplide_build_steps(project, factory, platform, debug, **kwargs):
  factory.addStep(ShellCommand(command=["cmake", "-DPLATFORM=" + platform, "-P", "build.cmake"],
    logfiles={"log": "com.ampl.ide.rcp.test/target/work/data/.metadata/.log"}))

name = "com.ampl.ide.repository/target/products/amplide."
uploads = [
  Upload(name + "linux32.tgz", platforms=plinux32),
  Upload(name + "linux64.tgz", platforms=plinux64),
  Upload(name + "win32.zip", platform="win32"),
  Upload(name + "win64.zip", platform="win64"),
  Upload(name + "mac64.tgz", platform="osx")]
add_project("amplide", debug=False,
  url="https://{}@github.com/ampl/amplide.git".format(key.BUILDBOT_KEY),
  submodule_command=["git", "config", "--file=.gitmodules", "submodule.site/jre.url",
                     "https://{}@github.com/ampl/jre.git".format(key.BUILDBOT_KEY)],
  use_submodules=True, build_steps=add_amplide_build_steps, uploads=uploads)

# AMPL API.
def add_amplapi_build_steps(project, factory, platform, debug, **kwargs):
  add_build_steps(project, factory, platform, debug, **kwargs)
  if debug:
    return
  win32 = platform.startswith("win")
  cmd = ["make", "package"]
  if win32:
    cmd = ['run-msbuild', '/p:Configuration=Release', 'PACKAGE.vcxproj']
  factory.addStep(ShellCommand(command=cmd))

add_project("amplapi",
  cmake_args_osx=["-DCMAKE_CXX_FLAGS=-std=c++11 -stdlib=libc++"],
  url="https://{}@github.com/ampl/amplapi.git".format(key.BUILDBOT_KEY),
  build_steps=add_amplapi_build_steps, uploads=['amplapi.zip'])

####### STATUS TARGETS

# 'status' is a list of Status Targets. The results of each build will be
# pushed to these targets. buildbot/status/*.py has a variety to choose from,
# including web pages, email senders, and IRC bots.

c['status'] = []

from buildbot.status import html
from buildbot.status.web import authz, auth
authz_cfg=authz.Authz(
    # change any of these to True to enable; see the manual for more
    # options
    auth=auth.BasicAuth([("admin","password")]),
    gracefulShutdown = False,
    forceBuild = True,
    forceAllBuilds = 'auth',
    pingBuilder = 'auth',
    stopBuild = 'auth',
    stopAllBuilds = 'auth',
    cancelPendingBuild = 'auth',
)
c['status'].append(html.WebStatus(http_port=8010, authz=authz_cfg))

####### PROJECT IDENTITY

# the 'title' string will appear at the top of this buildbot
# installation's html.WebStatus home page (linked to the
# 'titleURL') and is embedded in the title of the waterfall HTML page.

c['title'] = "AMPL"
c['titleURL'] = "https://github.com/ampl/mp"

# the 'buildbotURL' string should point to the location where the buildbot's
# internal web server (usually the html.WebStatus page) is visible. This
# typically uses the port number set in the Waterfall 'status' entry, but
# with an externally-visible host name which the buildbot cannot figure out
# without some help.

c['buildbotURL'] = "http://localhost:8010/"

####### DB URL

# This specifies what database buildbot uses to store change and scheduler
# state.  You can leave this at its default for all but the largest
# installations.
c['db_url'] = "sqlite:///state.sqlite"

